<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>用户管理</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link href="../../../../resources/lib/bui/css/dpl-min.css"
          th:href="@{/resources/lib/bui/css/dpl-min.css}"
          rel="stylesheet" />
    <link href="../../../../resources/lib/bui/css/bui-min.css"
          th:href="@{/resources/lib/bui/css/bui-min.css}"
          rel="stylesheet" />
    <script src="../../../../resources/lib/bui/js/jquery-1.8.1.min.js"
            th:src="@{/resources/lib/bui/js/jquery-1.8.1.min.js}"></script>
    <script src="../../../../resources/lib/bui/js/bui-min.js"
            th:src="@{/resources/lib/bui/js/bui-min.js}"></script>
    <script src="../../../../resources/lib/jquery/jquery.form.min.js"
            th:src="@{/resources/lib/jquery/jquery.form.min.js}"></script>
    <script src="../../../../resources/lib/jquery/jquery.util.js"
            th:src="@{/resources/lib/jquery/jquery.util.js}"></script>
</head>
<body>

<div style="padding: 10px;">
    <div class="row">
        <div class="span16">
            <div id="grid">
            </div>
        </div>
    </div>
    <div id="userFormContent" class="hide">
        <form class="form-horizontal" id="userForm" name="userForm" style="overflow-y:auto; overflow-x:hidden">
            <!--<legend>用户信息</legend>-->
            <div class="row" id="usernameDiv">
                <div class="control-group span7">
                    <label class="control-label" style="width: 80px"><s>*</s>账号：</label>
                    <div class="controls">
                        <input id="username" name="username" type="text" data-rules="{required:[true,'账号不能为空']}" maxlength="50" class="input-normal control-text">
                        <input id="id" name="id" type="hidden">
                    </div>
                </div>
            </div>
            <div class="row"  id="nameDiv">
                <div class="control-group span7">
                    <label class="control-label" style="width: 80px" ><s>*</s>姓名：</label>
                    <div class="controls">
                        <input id="name" name="name" type="text" data-rules="{required:[true,'姓名不能为空']}" maxlength="20" class="input-normal control-text">
                    </div>
                </div>
             </div>
            <div class="row" id="passwordDiv" hidden="true">
                <div class="control-group span7" >
                    <label class="control-label" style="width:80px" ><s>*</s>密码：</label>
                    <div class="controls">
                        <input id="password" name="password" type="password" data-rules="{required:[true,'密码不能为空']}" maxlength="20" class="input-normal control-text">
                    </div>
                </div>
            </div>
            <!--<div class="row" id="passwordReDiv" hidden="true">-->
                <!--<div class="control-group span7" >-->
                    <!--<label class="control-label" style="width: 80px" ><s>*</s>密码确认：</label>-->
                    <!--<div class="controls">-->
                        <!--<input id="passwordRe" name="passwordRe" type="password" data-rules="{required:[true,'密码确认不能为空'],equalTo:'#password'}" maxlength="20" class="input-normal control-text">-->
                    <!--</div>-->
                <!--</div>-->
            <!--</div>-->
            <div class="row" id="departmentDiv">
                <div class="control-group span7">
                    <label class="control-label" style="width: 80px"><s>*</s>部门：</label>
                    <div class="controls">
                        <div id="departmentCombox">
                        </div>
                    </div>
                </div>
            </div>
            <div class="row" id="mobilePhoneDiv">
                <div class="control-group span7">
                    <label class="control-label" style="width: 80px">移动电话：</label>
                    <div class="controls">
                        <input name="mobilePhone" id="mobilePhone" type="text" data-rules="{maxLength:[11,'最大长度为11'],number:true}" maxlength="11" class="input-normal control-text">
                    </div>
                </div>
            </div>
            <div class="row" id="phoneDiv">
                <div class="control-group span7">
                    <label class="control-label" style="width: 80px">固定电话：</label>
                    <div class="controls">
                        <input name="phone" id="phone" type="text" data-rules="{maxLength:[20,'最大长度为20'],minLength:[7,'最小长度为7']}" maxlength="20" class="input-normal control-text">
                    </div>
                </div>
            </div>
            <div class="row" id="typeDiv">
                <div class="control-group span7">
                    <label class="control-label" style="width: 80px"><s>*</s>类型：</label>
                    <div class="controls">
                        <select id="type" name="type">
                            <option value="0">用户</option>
                            <option value="1">管理员</option>
                        </select>
                    </div>
                </div>
            </div>
        </form>
        <div  id="permissionDiv" class="row hide">
            <div class="span8">
                <div id="t1">
                </div>
                <!--<h2>点击的节点</h2>-->
                <!--<div class="log well"></div>-->
            </div>
        </div>
    </div>
    <!-- script start-->
    <script th:inline="javascript" type="text/javascript">
        var Form = BUI.Form;
        var Grid = BUI.Grid;
        var Select = BUI.Select;
        var Data = BUI.Data;
        var Store = Data.Store;
        var type = 0;

        function IsBlank(e){           //不允许输入空格
            var k = window.event ? e.keyCode : e.which;
            if(k==32||k==188||k==222){
                return false;
            }
        }
        var userData = /*[[${userList}]]*/[];
        var permissionList = /*[[${permissionList}]]*/[];
        var BASE_URL = /*[[@{/}]]*/ '/';
        var grid = null;
        var editing = null;
        var checkedNodes = null;
        var flag = false;
        var tmStore = new Data.TreeStore({
            pidField: 'pid', //设置pid的字段名称
            data: permissionList,
            root: { id: '0', text: '首页' }
        });
        //由于这个树，不显示根节点，所以可以不指定根节点
        var tree = new BUI.Tree.TreeList({
            render : '#t1',
            store : tmStore,
            itemTpl: '<li id="{value}">{text}</li>', //列表项的模板
            expanded : true,
            idField: 'value',
            checkType: 'all', //checkType:勾选模式，提供了4中，all,onlyLeaf,none,custom
            showLine : true //显示连接线
        });
        tree.render();

        tree.on('checkedchange',function(ev){
            checkedNodes = tree.getCheckedNodes();
            flag = true;
        });

        function reverseRender(value, obj) {
            type = value;
            if (value == '0') {
                return "用户";
            } else if (value == '1') {
                return "管理员";
            }
        }

        var columns = [
            {title : '用户名',dataIndex :'username',width:150,editor : {xtype : 'text'}}, //editor中的定义等用于 BUI.Form.Field.Text的定义
            {title : '姓名',dataIndex :'name',width:150,editor : {xtype : 'text'}},
            {title : '所属部门',dataIndex : 'department', width:150,editor : {xtype :'text'}},
            {title : '用户类型',dataIndex : 'type',editor : {xtype :'text'},renderer : reverseRender, width : 150},
            {title : '移动电话',dataIndex :'mobilePhone',width:150,editor : {xtype : 'text'}},
            {title : '固定电话',dataIndex :'phone',width:150,editor : {xtype : 'text'}},
            {title : '操作',dataIndex:'h',width:150,renderer : function(){
                if(type==0){
                    return '<span class="grid-command btn-userEdit">编辑</span><span class="grid-command btn-permission">权限管理</span>'
                }else{
                    return '<span class="grid-command btn-userEdit">编辑</span>'
                }
            }}
        ];
        var departmentItems = /*[[${departmentList}]]*/['无','销售部','研发部','工程部','技术部','人力资源部'];
        var departmentCombox = new Select.Combox({
            render:'#departmentCombox',
            items: departmentItems,
            name:'department',
            id:'department',
            width:150
        });
        departmentCombox.render();

        $("input[name='department']").attr("maxlength","20");
        $("input[name='department']").attr("data-rules","{required:[true,'部门不能为空']}");


        editing = new Grid.Plugins.DialogEditing({
            contentId : 'userFormContent', //设置隐藏的Dialog内容
            triggerCls : 'btn-edit',//触发显示Dialog的样式
            editor : {
                title : '用户信息',
//                height : 380
                listeners:{
                    show: function(){
                        var userForm = this.get('form');
                        var username = userForm.getField('username');

                        username.set('remote',{
                            url :BASE_URL+ 'nh/system/users/checkUsername',
                            dataType:'json',//默认为字符串
                            callback : function(data){
                                if(data){
                                    return '账号已存在';
                                }else {
                                    return "";
                                }
                            }
                        },{silent : true});

                        username.on('remotestart',function(e,data){// 异步验证增加额外的参数
                            e.data.username = $('#username').val();
                            e.data.id = $('#id').val();
                        });
                        userForm.getField('username').clearCache();
                    },
                    cancel: function() {
                        var userForm = this.get('form');
                        userForm.clearErrors();
                        userForm.getField('username').clearCache();
                    },
                    accept:function(){
                        var userForm = this.get('form');
                        userForm.clearErrors();
                        userForm.getField('username').clearCache();
                        if(flag){
                            var idList = [];
                            for(var i=0;i<checkedNodes.length;i++){
                                idList.push(checkedNodes[i].id);
                            }
                            $.post(BASE_URL+"nh/system/users/insertOrUpdatePermission", {idList:JSON.stringify(idList),userId:$("#id").val()},function(data){
                                //tree.setItems(data);
                            })
                        }
                    }
                }
            },
            triggerSelected : false
        });

        var store = new Store({
            data : userData,
            pageSize :  10,
            autoLoad:true
        });
        grid = new Grid.Grid({
            render:'#grid',
            columns : columns,
            width : 800,
            height: 350,
            forceFit : true,
            tbar:{ //添加、删除
                items : [{
                    btnCls : 'button button-small',
                    text : '<i class="icon-plus"></i>添加',
                    listeners : {
                        'click' : addFunction
                    }
                },
                    {
                        btnCls : 'button button-small',
                        text : '<i class="icon-remove"></i>删除',
                        listeners : {
                            'click' : delFunction
                        }
                    },
                    {
                        btnCls : 'button button-small',
                        text : '<i class="icon-check"></i>修改密码',
                        listeners : {
                            'click' : changePassword
                        }
                    }]
            },
            bbar:{
                pagingBar : true
            },
            plugins : [editing,Grid.Plugins.RadioSelection],
            store : store
        });

        grid.render();

        grid.on('itemupdated',function(e){
            var obj = BUI.JSON.stringify(e.item);
            $.post(BASE_URL+"nh/system/users/insertOrUpdateUser", {user:obj},function(data){
                store.setResult(data);
                getDepartmentList();
            });
        });
        grid.on('rowcreated',function(e){
            var obj = BUI.JSON.stringify(e.record);
            if(e.record.id=='0'){
                $.post(BASE_URL+"nh/system/users/insertOrUpdateUser", {user:obj},function(data){
                    store.setResult(data);
                    getDepartmentList();
                })
            }
        });
//        var changePasswordUrl = /*[[@{/admin/system/users/changePassword}]]*/ 'admin/system/users/changePassword';
        grid.on('cellclick',function(ev){
            var sender = $(ev.domTarget); //点击的Dom
            var record = ev.record;
            if(record.name=='admin'){
                $("#delBtn").attr("disabled",true);
            }else{
                $("#delBtn").attr("disabled",false);
            }
            if(sender.hasClass('btn-permission')){

//                tree.expandAll();
                tree.clearAllChecked();
                $.post(BASE_URL+"nh/system/users/getPermission", {userId:record.id},function(data){
                    tree.expandAll();
                    for(var i=0;i<data.length;i++){
                        var node =tree.findNode(data[i]+"");
                        tree.setNodeChecked(node,true);
                    }
                    flag = false;
                })

                $('#permissionDiv').show();
                $('#passwordDiv').hide();
                $('#usernameDiv').hide();
                $('#nameDiv').hide();
                $('#departmentDiv').hide();
                $('#mobilePhoneDiv').hide();
                $('#phoneDiv').hide();
//                $('#passwordReDiv').hide();
                $('#typeDiv').hide();
                editing.get('editor').set('title','用户权限');
                editing.edit(record);

            }else if(sender.hasClass('btn-userEdit')){
                flag = false;
                $('#passwordDiv').hide();
                $('#permissionDiv').hide();
                $('#usernameDiv').show();
                $('#nameDiv').show();
                $('#departmentDiv').show();
                $('#emailDiv').show();
                $('#typeDiv').show();
                $('#mobilePhoneDiv').show();
                $('#phoneDiv').show();
//                $('#passwordReDiv').show();
                editing.get('editor').set('title','用户信息');
                editing.edit(record);
            }
        });

        var  userForm = new BUI.Form.HForm({
            srcNode : '#userForm'
        });
        $("#name").blur(function(){
            this.value = $.trim(this.value);
            userForm.getField(this.name).valid();
        });
        $("#username").blur(function(){
            this.value = $.trim(this.value);
            userForm.getField(this.name).valid();
        });
        $("input[name ='department']").blur(function(){
            this.value = $.trim(this.value);
            userForm.getField(this.name).valid();
        });
        $("#mobilePhone").blur(function(){
            this.value = $.trim(this.value);
            userForm.getField(this.name).valid();
        });

        //添加记录
        function addFunction(){
            var newData = {id : '0'};
            $('#passwordDiv').show();
            $('#permissionDiv').hide();
            $('#usernameDiv').show();
            $('#nameDiv').show();
            $('#departmentDiv').show();
            $('#emailDiv').show();
            $('#mobilePhoneDiv').show();
            $('#phoneDiv').show();
//            $('#passwordReDiv').show();
            $('#typeDiv').show();
            editing.add(newData,'id');
        }
        //删除选中的记录
        function delFunction(){
            var selections = grid.getSelection();
            if(selections[0].id==1){
                BUI.Message.Alert('admin用户无法删除');
                return;
            }
            var params = new Array();
            for(var i=0;i<selections.length;i++){
                params[i]=selections[i].id;
            };
            if(selections != null &&selections != ""){
                BUI.Message.Confirm('是否删除'+selections[0].username+'的用户信息？',function(){
                    $.post(BASE_URL+"nh/system/users/deleteUser", {params:BUI.JSON.stringify(params)});
                    store.remove(selections);
                    getDepartmentList();
                },'question');
            }else{
                BUI.Message.Alert("请选择要删除的用户");
            }
        }

        function changePassword(){
            var changePasswordUrl = BASE_URL+ 'nh/system/users/changePassword';
            var selections = grid.getSelection();
            if(selections == null ||selections == ""){
                BUI.Message.Alert("请选择要修改密码的用户");
                return;
            }
            var newPassword = prompt("请输入新密码:");
            if (newPassword) {
                console.log(newPassword);
                $.post(changePasswordUrl, {userId: selections[0].id, password: newPassword}, function(data){
                    console.log(data);
                    if (data.ok) {
                        BUI.Message.Alert("密码修改成功");
                    } else {
                        BUI.Message.Alert("应用程序错误");
                    }
                }, 'json');
            }
        }

    function getDepartmentList(){
        $.post(BASE_URL+"nh/system/users/getDepartmentList",function(data){
            departmentCombox.set('items',data);
        });
    }
    </script>
    <!-- script end -->
</div>
</body>
</html>